import React, { useState, useEffect } from 'react';
import { 
  Modal, 
  Form, 
  Input, 
  Select, 
  ColorPicker, 
  Slider, 
  Space,
  Typography,
  Row,
  Col,
  Card,
  Radio,
  Tabs,
  Switch
} from 'antd';
import { 
  ApartmentOutlined, 
  ArrowRightOutlined, 
  BgColorsOutlined, 
  InfoCircleOutlined,
  SettingOutlined
} from '@ant-design/icons';
import { getGraphTypeStyle } from '../../styles/graphThemes';

const { Option } = Select;
const { TextArea } = Input;
const { Text } = Typography;
const { TabPane } = Tabs;

/**
 * 关系编辑器组件
 * 支持不同图谱类型的关系样式编辑
 */
const RelationEditor = ({ 
  visible, 
  onCancel, 
  onSave, 
  relationData, 
  nodes = [],
  mode = 'add',
  relationTypeOptions = [],
  graphType = 'knowledge' // 添加图谱类型参数
}) => {
  const [form] = Form.useForm();
  const [relationColor, setRelationColor] = useState('#999');
  const [relationWidth, setRelationWidth] = useState(2);
  const [relationStyle, setRelationStyle] = useState('solid');
  const [isDirected, setIsDirected] = useState(true);
  const [activeTab, setActiveTab] = useState('basic');
  
  // 获取当前图谱类型的样式配置
  const graphStyle = getGraphTypeStyle(graphType);

  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && relationData) {
        form.setFieldsValue({
          label: relationData.label,
          type: relationData.type,
          source: relationData.source,
          target: relationData.target,
          description: relationData.description || '',
          strength: relationData.strength || 1,
          bidirectional: relationData.bidirectional || false
        });
        setRelationColor(relationData.color || graphStyle?.edgeColor?.({}) || '#999');
        setRelationWidth(relationData.width || 2);
        setRelationStyle(relationData.style || 'solid');
        setIsDirected(!relationData.bidirectional);
      } else {
        form.resetFields();
        setRelationColor(graphStyle?.edgeColor?.({}) || '#999');
        setRelationWidth(2);
        setRelationStyle('solid');
        setIsDirected(true);
      }
    }
  }, [visible, mode, relationData, form, graphStyle]);

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      const relationInfo = {
        ...relationData,
        ...values,
        color: relationColor,
        width: relationWidth,
        style: relationStyle,
        bidirectional: !isDirected
      };
      onSave(relationInfo);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 根据图谱类型获取默认关系类型选项
  const getDefaultRelationTypes = () => {
    const typeMap = {
      'knowledge': [
        { label: '包含', value: 'contains' },
        { label: '属于', value: 'belongs_to' },
        { label: '关联', value: 'related_to' },
        { label: '等价', value: 'equivalent' },
        { label: '部分-整体', value: 'part_of' }
      ],
      'mind': [
        { label: '包含', value: 'contains' },
        { label: '关联', value: 'related_to' },
        { label: '引用', value: 'references' }
      ],
      'concept': [
        { label: '关联', value: 'related_to' },
        { label: '定义', value: 'defines' },
        { label: '包含', value: 'contains' },
        { label: '对比', value: 'contrasts' }
      ],
      'social': [
        { label: '朋友', value: 'friend' },
        { label: '家人', value: 'family' },
        { label: '同事', value: 'colleague' },
        { label: '关注', value: 'follow' }
      ],
      'flow': [
        { label: '流向', value: 'flow_to' },
        { label: '条件', value: 'condition' },
        { label: '返回', value: 'return' }
      ],
      'ontology': [
        { label: '子类', value: 'subClassOf' },
        { label: '实例', value: 'instanceOf' },
        { label: '属性', value: 'hasProperty' },
        { label: '等价', value: 'equivalentTo' }
      ]
    };
    
    return typeMap[graphType] || [
      { label: '包含', value: 'contains' },
      { label: '属于', value: 'belongs_to' },
      { label: '关联', value: 'related_to' },
      { label: '等价', value: 'equivalent' },
      { label: '部分-整体', value: 'part_of' },
      { label: '导致', value: 'causes' },
      { label: '影响', value: 'affects' }
    ];
  };

  // 获取可用的线条样式选项
  const getLineStyleOptions = () => {
    const commonStyles = [
      { label: '实线', value: 'solid' },
      { label: '虚线', value: 'dashed' }
    ];
    
    const specialStyles = {
      'mind': [
        { label: '点线', value: 'dotted' },
        { label: '波浪线', value: 'wavy' }
      ],
      'flow': [
        { label: '粗实线', value: 'thick' }
      ],
      'concept': [
        { label: '双线', value: 'double' }
      ]
    };
    
    return [...commonStyles, ...(specialStyles[graphType] || [])];
  };

  const typeOptions = relationTypeOptions.length > 0 ? relationTypeOptions : getDefaultRelationTypes();
  const lineStyleOptions = getLineStyleOptions();

  const getNodeLabel = (nodeId) => {
    const node = nodes.find(n => n.id === nodeId);
    return node ? node.label : nodeId;
  };

  // 渲染关系预览
  const renderRelationPreview = () => {
    const sourceLabel = getNodeLabel(form.getFieldValue('source')) || '源节点';
    const targetLabel = getNodeLabel(form.getFieldValue('target')) || '目标节点';
    const relationLabel = form.getFieldValue('label') || '关系名称';
    
    // 根据关系类型设置不同的颜色
    const relationType = form.getFieldValue('type');
    const typeColorMap = {
      'contains': '#1677ff',
      'belongs_to': '#52c41a',
      'related_to': '#722ed1',
      'equivalent': '#fa8c16',
      'part_of': '#eb2f96',
      'causes': '#f5222d',
      'affects': '#faad14',
      'friend': '#1677ff',
      'family': '#52c41a',
      'colleague': '#722ed1',
      'follow': '#fa8c16',
      'flow_to': '#1677ff',
      'condition': '#fa8c16',
      'return': '#52c41a',
      'subClassOf': '#1677ff',
      'instanceOf': '#52c41a',
      'hasProperty': '#722ed1',
      'equivalentTo': '#fa8c16'
    };
    
    // 线条样式
    let lineStyle = {};
    switch (relationStyle) {
      case 'dashed':
        lineStyle = {
          borderTop: `${relationWidth}px dashed ${relationColor}`
        };
        break;
      case 'dotted':
        lineStyle = {
          borderTop: `${relationWidth}px dotted ${relationColor}`
        };
        break;
      case 'double':
        lineStyle = {
          borderTop: `${relationWidth}px double ${relationColor}`
        };
        break;
      case 'wavy':
        lineStyle = {
          height: relationWidth,
          background: `linear-gradient(45deg, transparent, transparent 49%, ${relationColor} 49%, ${relationColor} 51%, transparent 51%, transparent)`
        };
        break;
      case 'thick':
        lineStyle = {
          height: relationWidth * 2,
          backgroundColor: relationColor
        };
        break;
      default:
        lineStyle = {
          height: relationWidth,
          backgroundColor: relationColor
        };
    }

    return (
      <div style={{ 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center',
        padding: '20px',
        background: '#f5f5f5',
        borderRadius: '6px',
        minHeight: '120px'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
          <div style={{ textAlign: 'center' }}>
            <div
              style={{
                width: 24,
                height: 24,
                borderRadius: '50%',
                backgroundColor: typeColorMap[relationType] || '#1677ff',
                border: '2px solid #fff',
                boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                margin: '0 auto 4px'
              }}
            />
            <Text style={{ fontSize: '12px', color: '#666' }}>
              {sourceLabel}
            </Text>
          </div>
          
          <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
            <div
              style={{
                width: '80px',
                ...lineStyle
              }}
            />
            {isDirected && (
              <div
                style={{
                  width: 0,
                  height: 0,
                  borderTop: `${relationWidth * 2}px solid transparent`,
                  borderBottom: `${relationWidth * 2}px solid transparent`,
                  borderLeft: `${relationWidth * 3}px solid ${relationColor}`,
                  position: 'absolute',
                  right: '-3px',
                  top: '50%',
                  transform: 'translateY(-50%)'
                }}
              />
            )}
            <div
              style={{
                position: 'absolute',
                top: '-20px',
                left: '50%',
                transform: 'translateX(-50%)',
                fontSize: '12px',
                color: '#666',
                whiteSpace: 'nowrap',
                background: 'rgba(255, 255, 255, 0.8)',
                padding: '2px 4px',
                borderRadius: '4px'
              }}
            >
              {relationLabel}
            </div>
          </div>
          
          <div style={{ textAlign: 'center' }}>
            <div
              style={{
                width: 24,
                height: 24,
                borderRadius: '50%',
                backgroundColor: '#52c41a',
                border: '2px solid #fff',
                boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                margin: '0 auto 4px'
              }}
            />
            <Text style={{ fontSize: '12px', color: '#666' }}>
              {targetLabel}
            </Text>
          </div>
        </div>
      </div>
    );
  };

  return (
    <Modal
      title={
        <Space>
          <ApartmentOutlined />
          {mode === 'edit' ? '编辑关系' : '添加关系'}
          {graphStyle?.name && <Text type="secondary">({graphStyle.name})</Text>}
        </Space>
      }
      open={visible}
      onOk={handleSave}
      onCancel={onCancel}
      width={600}
      okText="保存"
      cancelText="取消"
    >
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane 
          tab={
            <span>
              <InfoCircleOutlined />
              基本信息
            </span>
          } 
          key="basic"
        >
          <Form
            form={form}
            layout="vertical"
            initialValues={{
              type: typeOptions[0]?.value || 'related_to',
              strength: 1,
              bidirectional: false
            }}
          >
            <Row gutter={16}>
              <Col span={10}>
                <Form.Item
                  name="source"
                  label="源节点"
                  rules={[{ required: true, message: '请选择源节点' }]}
                >
                  <Select placeholder="请选择源节点" showSearch optionFilterProp="children">
                    {nodes.map(node => (
                      <Option key={node.id} value={node.id}>
                        {node.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={4} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', paddingTop: '30px' }}>
                <ArrowRightOutlined style={{ fontSize: '16px', color: '#999' }} />
              </Col>
              <Col span={10}>
                <Form.Item
                  name="target"
                  label="目标节点"
                  rules={[{ required: true, message: '请选择目标节点' }]}
                >
                  <Select placeholder="请选择目标节点" showSearch optionFilterProp="children">
                    {nodes.map(node => (
                      <Option key={node.id} value={node.id}>
                        {node.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="label"
                  label="关系名称"
                  rules={[{ required: true, message: '请输入关系名称' }]}
                >
                  <Input placeholder="请输入关系名称" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="type"
                  label="关系类型"
                  rules={[{ required: true, message: '请选择关系类型' }]}
                >
                  <Select placeholder="请选择关系类型">
                    {typeOptions.map(option => (
                      <Option key={option.value} value={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              name="description"
              label="关系描述"
            >
              <TextArea 
                rows={3} 
                placeholder="请输入关系描述（可选）" 
              />
            </Form.Item>

            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="strength"
                  label="关系强度"
                >
                  <Slider
                    min={0.1}
                    max={2}
                    step={0.1}
                    marks={{
                      0.1: '弱',
                      1: '中',
                      2: '强'
                    }}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="关系方向"
                >
                  <Space>
                    <Switch 
                      checked={isDirected} 
                      onChange={setIsDirected} 
                      checkedChildren="有向" 
                      unCheckedChildren="无向" 
                    />
                    <Text type="secondary">
                      {isDirected ? '单向关系' : '双向关系'}
                    </Text>
                  </Space>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </TabPane>
        
        <TabPane 
          tab={
            <span>
              <BgColorsOutlined />
              外观设置
            </span>
          } 
          key="appearance"
        >
          <Card size="small">
            <Row gutter={16}>
              <Col span={8}>
                <div style={{ marginBottom: '16px' }}>
                  <Text strong style={{ display: 'block', marginBottom: '8px' }}>
                    线条颜色
                  </Text>
                  <ColorPicker
                    value={relationColor}
                    onChange={(color) => setRelationColor(color.toHexString())}
                    showText
                    size="large"
                  />
                </div>
              </Col>
              <Col span={8}>
                <div style={{ marginBottom: '16px' }}>
                  <Text strong style={{ display: 'block', marginBottom: '8px' }}>
                    线条粗细: {relationWidth}px
                  </Text>
                  <Slider
                    min={1}
                    max={8}
                    value={relationWidth}
                    onChange={setRelationWidth}
                    marks={{
                      1: '细',
                      4: '中',
                      8: '粗'
                    }}
                  />
                </div>
              </Col>
              <Col span={8}>
                <div>
                  <Text strong style={{ display: 'block', marginBottom: '8px' }}>
                    线条样式
                  </Text>
                  <Radio.Group
                    value={relationStyle}
                    onChange={(e) => setRelationStyle(e.target.value)}
                    size="small"
                    buttonStyle="solid"
                    style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}
                  >
                    {lineStyleOptions.map(style => (
                      <Radio.Button key={style.value} value={style.value}>
                        {style.label}
                      </Radio.Button>
                    ))}
                  </Radio.Group>
                </div>
              </Col>
            </Row>
          </Card>
          
          {/* 预览 */}
          <Card title="预览效果" size="small" style={{ marginTop: '16px' }}>
            {renderRelationPreview()}
          </Card>
        </TabPane>
        
        <TabPane 
          tab={
            <span>
              <SettingOutlined />
              高级设置
            </span>
          } 
          key="advanced"
        >
          <Card size="small">
            <Text type="secondary">
              根据关系类型，您可以添加自定义属性来丰富关系信息。
            </Text>
            
            <Form.List name="properties">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Row key={key} gutter={8} style={{ marginTop: '8px' }}>
                      <Col span={10}>
                        <Form.Item
                          {...restField}
                          name={[name, 'key']}
                          rules={[{ required: true, message: '请输入属性名' }]}
                        >
                          <Input placeholder="属性名" />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          {...restField}
                          name={[name, 'value']}
                          rules={[{ required: true, message: '请输入属性值' }]}
                        >
                          <Input placeholder="属性值" />
                        </Form.Item>
                      </Col>
                      <Col span={2}>
                        <Button 
                          type="text" 
                          danger 
                          onClick={() => remove(name)}
                        >
                          删除
                        </Button>
                      </Col>
                    </Row>
                  ))}
                  <Form.Item>
                    <Button 
                      type="dashed" 
                      onClick={() => add()} 
                      block
                      style={{ marginTop: '8px' }}
                    >
                      + 添加属性
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
            
            {graphType === 'flow' && (
              <div style={{ marginTop: '16px' }}>
                <Form.Item
                  name="condition"
                  label="流程条件"
                >
                  <Input placeholder="请输入流程条件（如果有）" />
                </Form.Item>
              </div>
            )}
            
            {graphType === 'ontology' && (
              <div style={{ marginTop: '16px' }}>
                <Form.Item
                  name="axiom"
                  label="本体公理"
                >
                  <TextArea 
                    rows={2} 
                    placeholder="请输入本体公理表达式（如果有）" 
                  />
                </Form.Item>
              </div>
            )}
          </Card>
        </TabPane>
      </Tabs>
    </Modal>
  );
};

export default RelationEditor;